package fm.dongman.modellib.source;

import org.jetbrains.annotations.NotNull;

import fm.dongman.animefm.contractlib.BaseDataSource;
import fm.dongman.animefm.contractlib.contract.FArticleContract;
import fm.dongman.animefm.contractlib.model.FArticleDataModel;
import fm.dongman.modellib.local.FArticleLocalDataSource;
import fm.dongman.modellib.remote.FArticleRemoteDataSource;

/**
 * 文章
 * Created by KUIGE on 2017/10/14.
 */

public class FArticleRepository implements FArticleContract.IFArticleDataSource {
    private static FArticleRepository SINGLETON; // 实
    private FArticleRemoteDataSource mRemoteDataSource;
    private FArticleLocalDataSource mLocalDataSource;

    private FArticleRepository(FArticleRemoteDataSource instance, FArticleLocalDataSource FArticleLocalDataSource) {
        mRemoteDataSource = instance;
        mLocalDataSource = FArticleLocalDataSource;
    }

    /**
     * 返回单例
     */
    public static FArticleRepository getInstance(FArticleRemoteDataSource instance, FArticleLocalDataSource FArticleLocalDataSource) {
        if (SINGLETON == null) {
            SINGLETON = new FArticleRepository(instance, FArticleLocalDataSource);
        }
        return SINGLETON;
    }

    @Override
    public void getData(@NotNull final LoadSourceCallback<? super FArticleDataModel> callback) {
        mRemoteDataSource.getData(new LoadSourceCallback<FArticleDataModel>() {
            @Override
            public void onDataLoaded(FArticleDataModel dataModel) {
                callback.onDataLoaded(dataModel);
            }

            @Override
            public void onDataLoadFiled() {
                loadLocalData(callback);
            }
        });
    }

    /**
     * 加载本地数据
     *
     * @param callback 回调
     */
    private void loadLocalData(final LoadSourceCallback<? super FArticleDataModel> callback) {
        mLocalDataSource.getData(new LoadSourceCallback<FArticleDataModel>() {
            @Override
            public void onDataLoaded(FArticleDataModel dataModel) {
                callback.onDataLoaded(dataModel);
            }

            @Override
            public void onDataLoadFiled() {
                callback.onDataLoadFiled();
            }
        });
    }

    @Override
    public void saveData(FArticleDataModel dataModel) {
        mLocalDataSource.saveData(dataModel);
    }

    @Override
    public void refreshData() {

    }

    @Override
    public void offLine() {
        mRemoteDataSource.offLine();
    }
}
